#include "SoundCache.h"

#include <iostream>

SoundCache* SoundCache::m_soundCache = NULL;

SoundCache::SoundCache()
{
    //ctor
}

SoundCache::~SoundCache()
{
    //dtor
}


/* GetSingleton */
SoundCache* SoundCache::GetSoundCache()
{
	if (not m_soundCache)
        m_soundCache = new SoundCache();
	return m_soundCache;
}

Sound* SoundCache::GetSound(CRstring soundName)
{
    Sound *sound;
    map<string, Sound *>::iterator iter;

    iter = m_Sounds.find(soundName);
    if (iter == m_Sounds.end())
    {
    #ifdef _DEBUG
        cout << "Error: Trying to get non-existant sound '" << soundName << "'. Trying to create." << endl;
    #endif
        // Sound was not found, let's try to create it
        string filename = "sounds/" + soundName + ".wav";

        sound = new Sound();
        if (sound->loadSound(filename) == PENJIN_OK) {
            m_Sounds[soundName] = sound;
            return sound;
        }
        #ifdef _DEBUG
        else
        {
            cout << "Failed to create sound '" << soundName << "'" << endl;
        }
        #endif
        return NULL;
    } else {
        return iter->second;
    }
}

void SoundCache::AddSound(CRstring soundName, CRstring soundFilename, CRbool singlePlay)
{
    Sound *sound;

    map<string, Sound *>::iterator iter;

    iter = m_Sounds.find(soundName);
    if (iter == m_Sounds.end())
    {
        sound = new Sound();
        sound->setSimultaneousPlay(singlePlay);
        if (sound->loadSound(soundFilename) == PENJIN_OK) {
            m_Sounds[soundName] = sound;
        }
        else
        {
            cout << "Error reading sound file (invalid path?): " << soundFilename << endl;
        }
    } // else we already have it, so do nothing
};

void SoundCache::AddSound(CRstring soundName, CRbool singlePlay)
{
    Sound *sound;

    map<string, Sound *>::iterator iter;

    iter = m_Sounds.find(soundName);
    if (iter == m_Sounds.end())
    {
        string filename = "sounds/" + soundName + ".wav";
        sound = new Sound();
        sound->setSimultaneousPlay(singlePlay);
        if (sound->loadSound(filename) == PENJIN_OK) {
            m_Sounds[soundName] = sound;
        }
        else
        {
            cout << "Error reading sound file from name: " << soundName << endl;
        }
    } // else we already have it, so do nothing
};

void SoundCache::PlaySound(CRstring soundName)
{
    Sound *sound = GetSound(soundName);
    if (sound) {
        sound->play();
    }
};

void SoundCache::PlaySound(CRstring soundName, CRuint volume)
{
    Sound *sound = GetSound(soundName);
    if (sound) {
        sound->setVolume(volume);
        sound->play();
    }
};

void SoundCache::Clear()
{
    map<string, Sound *>::iterator iter;

    for (iter = m_Sounds.begin(); iter != m_Sounds.end(); ++iter)
    {
        iter->second->stop();
        delete iter->second;
    }
    m_Sounds.clear();
};
